<?php

namespace app\api\controller;

use think\facade\Db;
use think\Response;
use app\common\controller\Frontend;

class Room extends Frontend
{
    protected array $noNeedLogin = ['getRooms', 'createRoom', 'updateRoom', 'deleteRoom', 'checkPassword'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 获取房间列表
     */
    public function getRooms(): Response
    {
        try {
            $rooms = Db::name('api_rooms')
                ->field('id, name, audio_count, password, create_time, update_time')
                ->order('create_time', 'desc')
                ->select()
                ->toArray();

            // 处理密码字段，不返回具体密码，只返回是否有密码
            foreach ($rooms as &$room) {
                $room['has_password'] = !empty($room['password']);
                unset($room['password']); // 不返回密码明文
            }

            $this->success('获取房间列表成功', $rooms);
        } catch (Exception $e) {
            $this->error('获取房间列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 创建新房间
     */
    public function createRoom(): Response
    {
        $data = $this->request->post();
        
        // 验证必填字段
        if (empty($data['name'])) {
            $this->error('房间名称不能为空');
        }

        try {
            $insertData = [
                'name' => $data['name'],
                'audio_count' => 0,
                'password' => !empty($data['password']) ? md5($data['password']) : null,
                'create_time' => time() * 1000,
                'update_time' => time() * 1000,
            ];

            $roomId = Db::name('api_rooms')->insertGetId($insertData);

            if ($roomId) {
                $this->success('创建房间成功', ['id' => $roomId, 'name' => $data['name']]);
            } else {
                $this->error('创建房间失败');
            }
        } catch (\Exception $e) {
            $this->error('创建房间失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新房间信息
     */
    public function updateRoom(): Response
    {
        $data = $this->request->post();
        $roomId = $this->request->post('id', 0);

        if (empty($roomId)) {
            $this->error('房间ID不能为空');
        }

        try {
            // 检查房间是否存在
            $room = Db::name('api_rooms')->where('id', $roomId)->find();
            if (!$room) {
                $this->error('房间不存在');
            }

            $updateData = [
                'update_time' => time() * 1000,
            ];

            if (isset($data['name']) && !empty($data['name'])) {
                $updateData['name'] = $data['name'];
            }

            if (isset($data['password'])) {
                $updateData['password'] = !empty($data['password']) ? md5($data['password']) : null;
            }

            if (isset($data['audio_count'])) {
                $updateData['audio_count'] = intval($data['audio_count']);
            }

            $result = Db::name('api_rooms')->where('id', $roomId)->update($updateData);

            if ($result !== false) {
                $this->success('更新房间成功');
            } else {
                $this->error('更新房间失败');
            }
        } catch (\Exception $e) {
            $this->error('更新房间失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除房间
     */
    public function deleteRoom(): Response
    {
        $roomId = $this->request->post('id', 0);

        if (empty($roomId)) {
            $this->error('房间ID不能为空');
        }

        try {
            // 检查房间是否存在
            $room = Db::name('api_rooms')->where('id', $roomId)->find();
            if (!$room) {
                $this->error('房间不存在');
            }

            $result = Db::name('api_rooms')->where('id', $roomId)->delete();

            if ($result) {
                $this->success('删除房间成功');
            } else {
                $this->error('删除房间失败');
            }
        } catch (\Exception $e) {
            $this->error('删除房间失败: ' . $e->getMessage());
        }
    }

    /**
     * 验证房间密码
     */
    public function checkPassword(): Response
    {
        $roomId = $this->request->post('room_id', 0);
        $password = $this->request->post('password', '');

        if (empty($roomId)) {
            $this->error('房间ID不能为空');
        }

        if (empty($password)) {
            $this->error('密码不能为空');
        }

        try {
            $room = Db::name('api_rooms')->where('id', $roomId)->find();
            if (!$room) {
                $this->error('房间不存在');
            }

            // 验证密码
            if ($password === $room['password']) {
                $this->success('验证成功');
            } else {
                $this->error('密码错误');
            }
        } catch (Exception $e) {
            $this->error('验证失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取房间详情
     */
    public function getRoomDetail(): Response
    {
        $roomId = $this->request->get('id', 0);

        if (empty($roomId)) {
            $this->error('房间ID不能为空');
        }

        try {
            $room = Db::name('api_rooms')
                ->field('id, name, audio_count, create_time, update_time')
                ->where('id', $roomId)
                ->find();

            if (!$room) {
                $this->error('房间不存在');
            }

            $this->success('获取房间详情成功', $room);
        } catch (\Exception $e) {
            $this->error('获取房间详情失败: ' . $e->getMessage());
        }
    }
}
